<template>
  <s-layout title="阵地预约" navbar="normal" :bgStyles="{ color: '#f5f5f5' }">
    <!-- Search Bar -->
    <view class="search-bar">
      <input
        v-model="state.searchKeyword"
        class="search-input"
        placeholder="搜索阵地名称、地址..."
        @confirm="handleSearch"
      />
      <text class="search-btn" @tap="handleSearch">🔍</text>
    </view>

    <!-- Filter Bar -->
    <view class="filter-bar">
      <text class="filter-title">🏷️ 阵地类型</text>
      <view class="filter-tags">
        <view
          v-for="(tag, index) in state.filterTags"
          :key="index"
          :class="['filter-tag', { active: state.activeFilter === index }]"
          @tap="handleFilterChange(index)"
        >
          {{ tag }}
        </view>
      </view>
    </view>

    <!-- Advanced Filter -->
    <view class="advanced-filter">
      <text class="advanced-filter-title">🔍 高级筛选</text>
      <view class="filter-row">
        <view class="filter-group">
          <text class="filter-label">功能室面积</text>
          <view class="custom-select" @tap="toggleDropdown('area')">
            <view class="filter-select">
              <text class="select-text">{{ state.selectedArea || '不限' }}</text>
              <text class="select-arrow">▼</text>
            </view>
            <view v-if="state.dropdownShow === 'area'" class="dropdown-menu">
              <view
                v-for="(option, index) in state.areaOptions"
                :key="index"
                class="dropdown-item"
                @tap.stop="selectArea(option.label)"
              >
                {{ option.label }}
              </view>
            </view>
          </view>
        </view>
        <view class="filter-group">
          <text class="filter-label">容纳人数</text>
          <view class="custom-select" @tap="toggleDropdown('capacity')">
            <view class="filter-select">
              <text class="select-text">{{ state.selectedCapacity || '不限' }}</text>
              <text class="select-arrow">▼</text>
            </view>
            <view v-if="state.dropdownShow === 'capacity'" class="dropdown-menu">
              <view
                v-for="(option, index) in state.capacityOptions"
                :key="index"
                class="dropdown-item"
                @tap.stop="selectCapacity(option.label)"
              >
                {{ option.label }}
              </view>
            </view>
          </view>
        </view>
        <view class="filter-group">
          <text class="filter-label">距离范围</text>
          <view class="custom-select" @tap="toggleDropdown('distance')">
            <view class="filter-select">
              <text class="select-text">{{ state.selectedDistance || '不限' }}</text>
              <text class="select-arrow">▼</text>
            </view>
            <view v-if="state.dropdownShow === 'distance'" class="dropdown-menu">
              <view
                v-for="(option, index) in state.distanceOptions"
                :key="index"
                class="dropdown-item"
                @tap.stop="selectDistance(option.label)"
              >
                {{ option.label }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- View Toggle -->
    <view class="view-toggle">
      <view class="toggle-btn">
        <view
          :class="['toggle-item', { active: state.viewMode === 'list' }]"
          @tap="state.viewMode = 'list'"
        >
          📋 列表
        </view>
        <view
          :class="['toggle-item', { active: state.viewMode === 'map' }]"
          @tap="state.viewMode = 'map'"
        >
          🗺️ 地图
        </view>
      </view>
      <text class="toggle-label">共找到 {{ filteredVenues.length }} 个阵地</text>
    </view>

    <!-- Venue List -->
    <view class="venue-list">
      <view
        v-for="venue in filteredVenues"
        :key="venue.id"
        class="venue-card"
        @tap="handleVenueClick(venue)"
      >
        <view class="venue-header">
          <view class="venue-info">
            <text class="venue-name">{{ venue.name }}</text>
            <text class="venue-category">{{ venue.category }}</text>
          </view>
          <view :class="['venue-status', getStatusClass(venue.status)]">
            {{ venue.status }}
          </view>
        </view>

        <view class="venue-details">
          <view class="detail-item">
            <text class="detail-icon">📍</text>
            <text class="detail-text">{{ venue.address }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-icon">⏰</text>
            <text class="detail-text">开放时间：{{ venue.openTime }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-icon">📐</text>
            <text class="detail-text">阵地面积：{{ venue.area }}平方米</text>
          </view>
          <view class="detail-item">
            <text class="detail-icon">👥</text>
            <text class="detail-text">容纳人数：{{ venue.capacity }}人</text>
          </view>
          <view class="detail-item">
            <text class="detail-icon">🚗</text>
            <text class="detail-text">距离您：{{ venue.distance }}km</text>
          </view>
        </view>

        <view class="venue-features">
          <text v-for="(tag, idx) in venue.features" :key="idx" class="feature-tag">{{ tag }}</text>
        </view>

        <view class="venue-actions">
          <button class="btn btn-secondary" @tap.stop="handleCall(venue)">📞 联系</button>
          <button class="btn btn-primary" @tap.stop="handleReserve(venue)">
            {{ venue.status === '可预约' ? '立即预约' : venue.status === '使用中' ? '预约排队' : '查看详情' }}
          </button>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { reactive, computed } from 'vue'
import sheep from '@/sheep'

const state = reactive({
  searchKeyword: '',
  activeFilter: 0,
  filterTags: ['全部', '实践中心', '文化广场', '社区服务站', '志愿者之家', '图书馆'],
  dropdownShow: '', // 控制哪个下拉框显示
  areaOptions: [
    { label: '不限', value: '' },
    { label: '小型（0-200㎡）', value: 'small' },
    { label: '中型（200-500㎡）', value: 'medium' },
    { label: '大型（500-1000㎡）', value: 'large' },
    { label: '超大型（1000㎡+）', value: 'xlarge' }
  ],
  capacityOptions: [
    { label: '不限', value: '' },
    { label: '小型（0-50人）', value: 'small' },
    { label: '中型（50-200人）', value: 'medium' },
    { label: '大型（200-500人）', value: 'large' },
    { label: '超大型（500人+）', value: 'xlarge' }
  ],
  distanceOptions: [
    { label: '不限', value: '' },
    { label: '附近（0-1km）', value: 'near' },
    { label: '中距离（1-3km）', value: 'medium' },
    { label: '较远（3-5km）', value: 'far' },
    { label: '很远（5km+）', value: 'veryFar' }
  ],
  selectedArea: '不限',
  selectedCapacity: '不限',
  selectedDistance: '不限',
  viewMode: 'list',
  venueList: [
    {
      id: 1,
      name: '新时代文明实践中心',
      category: '实践中心',
      address: '人民路123号',
      area: 500,
      capacity: 200,
      openTime: '08:00-22:00',
      distance: 0.5,
      features: ['💻 多媒体设备', '🎤 音响系统', '🅿️ 免费停车', '♿ 无障碍通道'],
      status: '可预约',
      phone: '010-12345678'
    },
    {
      id: 2,
      name: '社区文化广场',
      category: '文化广场',
      address: '文化街45号',
      area: 1200,
      capacity: 500,
      openTime: '06:00-24:00',
      distance: 1.2,
      features: ['🎭 舞台设施', '💡 LED屏幕', '🚻 公共设施', '🌳 绿化环境'],
      status: '使用中',
      phone: '010-87654321'
    },
    {
      id: 3,
      name: '志愿者服务站',
      category: '社区服务站',
      address: '建设路88号',
      area: 120,
      capacity: 50,
      openTime: '09:00-18:00',
      distance: 2.1,
      features: ['☕ 休息区', '📚 图书角', '🖥️ 办公设备', '📶 免费WiFi'],
      status: '可预约',
      phone: '010-11223344'
    }
  ]
})

const filteredVenues = computed(() => {
  let result = state.venueList

  // Filter by search keyword
  if (state.searchKeyword) {
    result = result.filter(
      (v) =>
        v.name.includes(state.searchKeyword) ||
        v.address.includes(state.searchKeyword)
    )
  }

  // Filter by type
  if (state.activeFilter > 0) {
    const filterType = state.filterTags[state.activeFilter]
    result = result.filter((v) => v.category === filterType)
  }

  // Filter by area
  if (state.selectedArea && state.selectedArea !== '不限') {
    const areaOption = state.areaOptions.find(opt => opt.label === state.selectedArea)
    if (areaOption?.value) {
      result = result.filter((v) => {
        if (areaOption.value === 'small') return v.area < 200
        if (areaOption.value === 'medium') return v.area >= 200 && v.area < 500
        if (areaOption.value === 'large') return v.area >= 500 && v.area < 1000
        if (areaOption.value === 'xlarge') return v.area >= 1000
        return true
      })
    }
  }

  // Filter by capacity
  if (state.selectedCapacity && state.selectedCapacity !== '不限') {
    const capacityOption = state.capacityOptions.find(opt => opt.label === state.selectedCapacity)
    if (capacityOption?.value) {
      result = result.filter((v) => {
        if (capacityOption.value === 'small') return v.capacity < 50
        if (capacityOption.value === 'medium') return v.capacity >= 50 && v.capacity < 200
        if (capacityOption.value === 'large') return v.capacity >= 200 && v.capacity < 500
        if (capacityOption.value === 'xlarge') return v.capacity >= 500
        return true
      })
    }
  }

  // Filter by distance
  if (state.selectedDistance && state.selectedDistance !== '不限') {
    const distanceOption = state.distanceOptions.find(opt => opt.label === state.selectedDistance)
    if (distanceOption?.value) {
      result = result.filter((v) => {
        if (distanceOption.value === 'near') return v.distance < 1
        if (distanceOption.value === 'medium') return v.distance >= 1 && v.distance < 3
        if (distanceOption.value === 'far') return v.distance >= 3 && v.distance < 5
        if (distanceOption.value === 'veryFar') return v.distance >= 5
        return true
      })
    }
  }

  return result
})

const handleSearch = () => {
  // Trigger re-filter
  console.log('Searching for:', state.searchKeyword)
}

const handleFilterChange = (index) => {
  state.activeFilter = index
}

const toggleDropdown = (type) => {
  if (state.dropdownShow === type) {
    state.dropdownShow = ''
  } else {
    state.dropdownShow = type
  }
}

const selectArea = (label) => {
  state.selectedArea = label
  state.dropdownShow = ''
}

const selectCapacity = (label) => {
  state.selectedCapacity = label
  state.dropdownShow = ''
}

const selectDistance = (label) => {
  state.selectedDistance = label
  state.dropdownShow = ''
}

const handleAreaChange = (e) => {
  state.selectedArea = state.areaOptions[e.detail.value].label
}

const handleCapacityChange = (e) => {
  state.selectedCapacity = state.capacityOptions[e.detail.value].label
}

const handleDistanceChange = (e) => {
  state.selectedDistance = state.distanceOptions[e.detail.value].label
}

const handleVenueClick = (venue) => {
  sheep.$router.go(`/pages/cmt/venue-detail?id=${venue.id}`)
}

const handleReserve = (venue) => {
  if (venue.status === '可预约') {
    sheep.$router.go(`/pages/cmt/venue-reserve?id=${venue.id}`)
  } else {
    handleVenueClick(venue)
  }
}

const handleCall = (venue) => {
  uni.makePhoneCall({
    phoneNumber: venue.phone
  })
}

const getStatusClass = (status) => {
  if (status === '可预约') return 'status-available'
  if (status === '使用中') return 'status-busy'
  if (status === '已满') return 'status-full'
  return ''
}
</script>

<style lang="scss" scoped>
.search-bar {
  background: white;
  margin: 30rpx;
  border-radius: 40rpx;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

  .search-input {
    flex: 1;
    font-size: 28rpx;
  }

  .search-btn {
    font-size: 32rpx;
    color: #ff6b00;
    cursor: pointer;
  }
}

.filter-bar {
  background: white;
  margin: 0 30rpx 30rpx;
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

  .filter-title {
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
  }

  .filter-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;

    .filter-tag {
      padding: 12rpx 24rpx;
      border-radius: 30rpx;
      background: #f0f2f5;
      font-size: 24rpx;
      color: #666;
      transition: all 0.3s;

      &.active {
        background: linear-gradient(135deg, #ff6b00, #ffa726);
        color: white;
      }
    }
  }
}

.advanced-filter {
  background: white;
  margin: 0 30rpx 30rpx;
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

  .advanced-filter-title {
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
  }

  .filter-row {
    display: flex;
    gap: 12rpx;
    align-items: flex-end;

    .filter-group {
      flex: 1;
      min-width: 0;

      .filter-label {
        font-size: 22rpx;
        color: #666;
        margin-bottom: 8rpx;
        display: block;
      }

      .custom-select {
        position: relative;
      }

      .filter-select {
        width: 100%;
        padding: 12rpx 10rpx;
        border: 2rpx solid #e0e0e0;
        border-radius: 16rpx;
        font-size: 20rpx;
        color: #333;
        background: white;
        display: flex;
        align-items: center;
        justify-content: space-between;
        min-height: 60rpx;
        box-sizing: border-box;

        .select-text {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .select-arrow {
          font-size: 18rpx;
          color: #999;
          margin-left: 6rpx;
          flex-shrink: 0;
        }
      }

      .dropdown-menu {
        position: absolute;
        top: 100%;
        left: 0;
        min-width: 100%;
        width: max-content;
        background: white;
        border: 2rpx solid #e0e0e0;
        border-top: none;
        border-radius: 0 0 16rpx 16rpx;
        box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
        z-index: 100;
        max-height: 400rpx;
        overflow-y: auto;
        margin-top: -16rpx;

        .dropdown-item {
          padding: 16rpx 20rpx;
          font-size: 20rpx;
          color: #333;
          border-bottom: 1rpx solid #f0f0f0;
          transition: background 0.2s;
          white-space: nowrap;

          &:last-child {
            border-bottom: none;
          }

          &:active {
            background: #f5f5f5;
          }
        }
      }
    }
  }
}

.view-toggle {
  background: white;
  margin: 0 30rpx 30rpx;
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toggle-btn {
    display: flex;
    gap: 10rpx;

    .toggle-item {
      padding: 16rpx 30rpx;
      border-radius: 40rpx;
      background: #f0f2f5;
      font-size: 24rpx;
      color: #666;
      transition: all 0.3s;
      cursor: pointer;

      &.active {
        background: linear-gradient(135deg, #ff6b00, #ffa726);
        color: white;
      }
    }
  }

  .toggle-label {
    font-size: 24rpx;
    color: #999;
  }
}

.venue-list {
  margin: 0 30rpx;

  .venue-card {
    background: white;
    border-radius: 32rpx;
    padding: 40rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.08);
    transition: all 0.3s;
    cursor: pointer;

    .venue-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 30rpx;

      .venue-info {
        flex: 1;

        .venue-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }

        .venue-category {
          background: linear-gradient(135deg, #fff3e0, #ffecb3);
          color: #ff6b00;
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
          font-size: 20rpx;
          display: inline-block;
        }
      }

      .venue-status {
        padding: 10rpx 20rpx;
        border-radius: 24rpx;
        font-size: 22rpx;
        font-weight: bold;

        &.status-available {
          background: #d4edda;
          color: #155724;
        }

        &.status-busy {
          background: #fff3cd;
          color: #856404;
        }

        &.status-full {
          background: #f8d7da;
          color: #721c24;
        }
      }
    }

    .venue-details {
      margin-bottom: 30rpx;

      .detail-item {
        display: flex;
        align-items: center;
        gap: 16rpx;
        margin-bottom: 16rpx;
        font-size: 26rpx;
        color: #666;

        .detail-icon {
          font-size: 28rpx;
        }

        .detail-text {
          font-size: 26rpx;
          color: #666;
        }
      }
    }

    .venue-features {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
      margin-bottom: 30rpx;

      .feature-tag {
        background: #f0f2f5;
        color: #666;
        padding: 6rpx 12rpx;
        border-radius: 16rpx;
        font-size: 22rpx;
        white-space: nowrap;
      }
    }

    .venue-actions {
      display: flex;
      gap: 20rpx;

      .btn {
        flex: 1;
        padding: 16rpx 32rpx;
        border-radius: 40rpx;
        border: none;
        font-size: 26rpx;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        line-height: 1;

        &::after {
          border: none;
        }

        &.btn-primary {
          background: linear-gradient(135deg, #ff6b00, #ffa726);
          color: white;
        }

        &.btn-secondary {
          background: #fff3e0;
          color: #ff6b00;
        }
      }
    }
  }
}
</style>
